package dp.util;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
 *
 * @author chensh
 */
public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper();
    
    static{
        //设置日期（Date、Timestamp）的格式
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //jackson2.6.1之后需要加上这句
        mapper.setTimeZone(TimeZone.getDefault());
        //序列化设置,序列化成json字符串的时候不包含null值,针对Map类
        mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
//      mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        //序列化设置,序列化成json字符串的时候不包含null值,针对POJO类
        mapper.setSerializationInclusion(Include.NON_NULL);
        
        //反序列化设置,忽略JSON字符串中存在而Java对象实际没有的属性，否则json字符串中的属性如果bean里面没有的话会报错
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //允许反序列化不带双引号的key, mapper.enable>=2.5.3  mapper.configure<=2.3.2
    	mapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
//        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    }
    
    public static void main(String[] args){
    	String text = "[{\"name\":\"陈\"}]";
    	List<Map> list = JsonUtil.toObjectList(text, Map.class);
    	System.out.println(list);
    	String str = JsonUtil.toJSONString(list);
    	System.out.println(str);
    	
    	text = "[{name:\"陈\"}]";
    	list = JsonUtil.toObjectList(text, Map.class);
    	str = JsonUtil.toJSONString(list);
    	System.out.println(str);
    	
    	Map t = new HashMap();
    	t.put("time", new Date());
    	t.put("name", null);
    	t.put("xx", new Timestamp(new Date().getTime()));
    	System.out.println(JsonUtil.toJSONString(t));
    	
    	User user = new User();
    	user.setName("绿卡绝对是");
    	System.out.println(JsonUtil.toJSONString(user));
    	
    	user = JsonUtil.toObject("{name:\"陈\",age:30}", User.class);
    	System.out.println(JsonUtil.toJSONString(user));
    	
    	Map userMap = JsonUtil.toObject("{name:\"陈\",age:30}", Map.class);
    	System.out.println(userMap);
    	
    	List<User> userList = JsonUtil.toObjectList("[{name:\"陈\",age:30}]", User.class);
    	System.out.println(userList.get(0).getName());
    	
    	JsonNode jsonNode = JsonUtil.toJsonNode("[{name:{a1:20,a2:50},age:30}]");
    	System.out.println(JsonUtil.toObjectArray(jsonNode, Map.class)[0]);
    	
    	//对象转化成JsonNode
    	System.out.println(JsonUtil.getObjectMapper().valueToTree(user).getClass());
    	System.out.println(JsonUtil.getObjectMapper().convertValue(userList, JsonNode.class));
    }

    private JsonUtil(){}

    public static ObjectMapper getObjectMapper(){
        return mapper;
    }
    
    /**
     * 将json字符串转换成JsonNode
     * 
     * @param json
     * @return
     */
    public static JsonNode toJsonNode(String json){
    	try {
            return mapper.readTree(json);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toJsonNode发生错误", e);
        }
    }

    /**
     * 将Object转化成JSON String
     * @param obj
     * @return
     */
    public static String toJSONString(Object obj){
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toJSONString发生错误", e);
        }
    }
    
    /**
     * 将Object转化成JSON byte[]
     * @param obj
     * @return
     */
    public static byte[] toJSONBytes(Object obj){
        try {
            return mapper.writeValueAsBytes(obj);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toJSONBytes发生错误", e);
        }
    }

    /**
     * 将json字符串转换到Object
     * @param json json字符串
     * @param clazz 返回类型
     * @return 转换结果
     */
    public static <T> T toObject(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObject发生错误", e);
        }
    }
    
    /**
     * 将byte[]字符串转换到Object
     * @param json byte[]
     * @param clazz 返回类型
     * @return 转换结果
     */
    public static <T> T toObject(byte[] json, Class<T> clazz){
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObject发生错误", e);
        }
    }
    
    /**
     * 将JsonNode转换到Object
     * @param jsonNode jsonNode
     * @param clazz 返回类型
     * @return 转换结果
     */
    public static <T> T toObject(JsonNode jsonNode, Class<T> clazz){
        try {
            return mapper.readValue(jsonNode.traverse(), clazz);
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObject发生错误", e);
        }
    }
    
    /**
     * 将json字符串转换到Object List
     * @param json json字符串
     * @param clazz 返回类型
     * @return 转换结果
     */
	public static <T> List<T> toObjectList(String json, Class<T> clazz){
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectList发生错误", e);
        }
    }
	
	/**
     * 将byte[]字符串转换到Object List
     * @param json byte[]
     * @param clazz 返回类型
     * @return 转换结果
     */
    public static <T> List<T> toObjectList(byte[] json, Class<T> clazz){
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectList发生错误", e);
        }
    }
    
    /**
	 * 将JsonNode转换到Object List
	 * @param jsonNode jsonNode
	 * @param clazz 返回类型
	 * @return 转换结果
	 */
	public static <T> List<T> toObjectList(JsonNode jsonNode, Class<T> clazz){
	    try {
            return mapper.readValue(jsonNode.traverse(), mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectList发生错误", e);
        }
	}
	
	/**
	 * 将json字符串转换到Object Array
	 * @param json json字符串
	 * @param clazz 返回类型
	 * @return 转换结果
	 */
    public static <T> T[] toObjectArray(String json, Class<T> clazz){
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructArrayType(clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectArray发生错误", e);
        }
    }
    
    /**
     * 将byte[]字符串转换到Object Array
     * @param json byte[]
     * @param clazz 返回类型
     * @return Object
     */
    public static <T> T[] toObjectArray(byte[] json, Class<T> clazz){
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructArrayType(clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectArray发生错误", e);
        }
    }
    
    /**
     * 将jJsonNode转换到Object Array
     * @param json jsonNode
     * @param clazz 返回类型
     * @return 转换结果
     */
    public static <T> T[] toObjectArray(JsonNode jsonNode, Class<T> clazz){
        try {
            return mapper.readValue(jsonNode.traverse(), mapper.getTypeFactory().constructArrayType(clazz));
        } catch (Exception e) {
            throw new RuntimeException("JsonUtil.toObjectArray发生错误", e);
        }
    }
    
   static class User {
    	String name;
    	String address;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getAddress() {
    		return address;
    	}
    	public void setAddress(String address) {
    		this.address = address;
    	}
    }
}
